package GeneralObjects;

import java.io.IOException;
import java.util.ArrayList;

import ArithmeticObjects.Group;
import utils.ByteTree;

/**
 * Representing an array of CipherTexts
 * @author Idan
 */
public class CipherTextArray {
	
	private ArrayList<CipherText> lst;
//	private ByteTree bt;
	
	/**
	 * creates a CipherText from a ByteTree representing it and a Group indicating its order
	 * @param bt the ByteTree representing the CipherTextArray
	 * @param Gq the Group indicating its order
	 * @throws Exception in case the CipherTexts could not be constructed
	 */
	public CipherTextArray(ByteTree bt, Group Gq) throws Exception
	{
//		this.bt = bt;
		lst = new ArrayList<CipherText>();
		for (int i=0; i<bt.getChild(0).getNumOfChildren(); i++)
			lst.add(new CipherText(bt.getChild(0).getChild(i), bt.getChild(1).getChild(i), Gq));
	}
	
	/**
	 * @return the ByteTree representation of the CipherTextArray
	 * @throws IOException 
	 */
	public ByteTree getByteTree() throws IOException{
//		return bt;
		ByteTree rightBt = ByteTree.CreateNode();
		ByteTree leftBt = ByteTree.CreateNode();
		for (int i=0; i < this.getArraySize(); i++) {
			leftBt.AddChildToNode(lst.get(i).getByteTree().getChild(0));
			rightBt.AddChildToNode(lst.get(i).getByteTree().getChild(1));
		}
		return ByteTree.CreateNode().AddMultiChildsToNode(leftBt,rightBt);
	}
	
	/**
	 * @param i the index of the required CipherText in the array
	 * @return the CipherText at the i'th position
	 */
	public CipherText getCipherTextForIndex(int i)
	{
		return lst.get(i);
	}
	
	/**
	 * @return the number of CipherTexts in the array
	 */
	public int getArraySize() {
		return lst.size();
	}
	
	/**
	 * compares the current CipherTextArray to another one
	 * @param c the other CipherTextArray to compare to
	 * @return 0 if the arrays are the same and 1 otherwise
	 * @throws Exception in case the matching CipherTexts are not of the same structure
	 */
	public int compareTo(CipherTextArray c) throws Exception{
		if (this.getArraySize() != c.getArraySize())
			return 1;
		else {
			for (int i=0; i<lst.size(); i++)
				if (lst.get(i).compareTo(c.getCipherTextForIndex(i)) != 0)
					return 1;
		}
		return 0;
	}

}
